#include <QtGui>

#include <QDebug>
#include "robot.h"
#include "core.h"
#include "viewerwidget.h"
#include "glwidget.h"
#include "jointdata.h"


viewerWidget::viewerWidget(Robot *robot, Core *core)
{
	robotPointer = robot;
	corePointer = core;
	glWidget = new GLWidget(robotPointer);
	
	connect(corePointer, SIGNAL(robotUpdated()), glWidget,SLOT(updateWidget()));
	connect(corePointer, SIGNAL(robotLoaded()), glWidget, SLOT(robotLoaded()));

	generateControls();
	
	endEffector = new JointData(robotPointer, QString("End Effector"), robotPointer->jointList.size()-1);
	userSelected = new JointData(robotPointer, QString("Selected Joint"), -1);

	endEffector->setFixedSize(QSize(265, 150));
	userSelected->setFixedSize(QSize(265, 150));

	connect(corePointer, SIGNAL(robotUpdated()), endEffector, SLOT(updateSelf()));

	connect(corePointer, SIGNAL(robotUpdated()), userSelected, SLOT(updateSelf()));
	connect(this, SIGNAL(putFocusOn(int)), userSelected, SLOT(setJoint(int)));
	
	mainLayout = new QGridLayout;
	mainLayout->addWidget(glWidget, 0, 0, 5, 2);
	
	for (int i=0; i<robotPointer->jointList.size(); i++)
	{
	    mainLayout->addWidget(jointControlList[i], i, 2);
	}
	mainLayout->addWidget(endEffector, 5, 0);
	mainLayout->addWidget(userSelected,5, 1);
	setLayout(mainLayout);

	focusOn(-1);
}


void viewerWidget::generateControls()
{
    JointControl *jointControlTemp;
    jointControlList.clear();

    for(int i=0; i<robotPointer->jointList.size(); i++)
	{
	    jointControlTemp = new JointControl(i, robotPointer->jointList[i].getType(),
						    robotPointer->jointList[i].getMinimum(),
						    robotPointer->jointList[i].getMaximum(),
						    robotPointer->jointList[i].getCurrentActuation());

	    jointControlList.append(jointControlTemp);

	    jointControlList[i]->setFixedSize(QSize(400, 82));

	    connect(jointControlList[i], SIGNAL(valueChanged(int,float)), corePointer, SLOT(adjustJoint(int, float)));
	    connect(this, SIGNAL(putFocusOn(int)), jointControlList[i], SLOT(setFocus(int)));
	    connect(jointControlList[i], SIGNAL(grabFocus(int)), this, SLOT(focusOn(int)));
	}

    jointControlTemp = NULL;
}

void viewerWidget::focusOn(int joint)	//SLOT
{
	jointFocus = joint;
	emit(putFocusOn(joint));
}


void viewerWidget::robotLoaded()	//SLOT
{
	for (int i=0; i<jointControlList.size(); i++)
	{
		delete jointControlList[i];
	}
	jointControlList.clear();
	
	generateControls();
	
	for (int i=0; i<robotPointer->jointList.size(); i++)
	{
	    mainLayout->addWidget(jointControlList[i], i, 2);
	}
	
	//reset endEffector label to last link in new robot
	endEffector->setJoint(robotPointer->jointList.size()-1);
}

void viewerWidget::setRobot(Robot *robot)
{
	robotPointer = robot;
	generateControls();
}

void viewerWidget::resetView()
{
	glWidget->resetView();
}
